//
//  BaseNavigationController.swift
//  NetProject
//
//  Created by EDY on 2021/11/1.
//

import Foundation
import UIKit

class BaseNavigationController : UINavigationController,UINavigationControllerDelegate, UIGestureRecognizerDelegate{
    
    var popDelegate : UIGestureRecognizerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.navigationBar.setBarColor(HEXRGBCOLOR(0x287890))
        
    }
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        if (self.viewControllers.count > 0) { // 如果现在push的不是栈底控制器(最先push进来的那个控制器)
            
            viewController.hidesBottomBarWhenPushed = true;
            viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "back"), style: .plain, target: self, action: #selector(back))
        }
        super.pushViewController(viewController, animated: animated)
        //解决iPhoneX push页面时tabbar上移问题
        if (isPhoneXAbove) {
            
            var frame = self.tabBarController?.tabBar.frame;
            if (frame != nil) {
                frame!.origin.y = kCNScreenH - frame!.size.height;
                self.tabBarController!.tabBar.frame = frame!;
            }
            
        }
    }
    
    @objc func back() -> Void{
        self.popViewController(animated: true)
    }
}

public extension UINavigationBar {
    
    func setBarColor(_ barColor: UIColor?) {
        
        if barColor != nil && barColor!.cgColor.alpha == 0 {
            // if transparent color then use transparent nav bar
            self.setBackgroundImage(UIImage(), for: .default)
            self.hideShadow(true)
        }
        else if barColor != nil {
            // use custom color
            self.setBackgroundImage(self.image(with: barColor!), for: .default)
            self.hideShadow(false)
        }
        else {
            // restore original nav bar color
            self.setBackgroundImage(nil, for: .default)
            self.hideShadow(false)
        }
    }
    
    func hideShadow(_ doHide: Bool) {
        self.shadowImage = doHide ? UIImage() : nil
    }
    
    func image(with color: UIColor) -> UIImage {
        let rect = CGRect(x: CGFloat(0.0), y: CGFloat(0.0), width: CGFloat(1.0), height: CGFloat(1.0))
        UIGraphicsBeginImageContext(rect.size)
        if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(rect)
        }
        let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
}
